﻿using B.S.Data.MES.API.Applications.ShenPi.Command;
using B.S.Domain.Node;
using B.S.Domain.Process.ProcessrouteName;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Data.MES.API.Applications.ShenPi.CommandHandlers
{
    public class NodeCommandHandlers : IRequestHandler<NodeCommand, APIRequst<int>>
    {
        private readonly IBaseRepository<Nodeinfo> nodeRepository;
        private readonly IBaseRepository<Processroute> processRepository;

        public NodeCommandHandlers(IBaseRepository<Nodeinfo> nodeRepository, IBaseRepository<Processroute> processRepository)
        {
            this.nodeRepository = nodeRepository;
            this.processRepository = processRepository;
        }

        public async Task<APIRequst<int>> Handle(NodeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 根据ID查询工艺路线
                var processroute = await processRepository.GetById(request.ProcessRouteId);
                
                if (processroute == null)
                {
                    return new APIRequst<int>
                    {
                        Code = RequstCode.成功,
                        Msg = $"未找到ID为{request.ProcessRouteId}的工艺路线",
                        Data = 0
                    };
                }

                if (string.IsNullOrEmpty(processroute.nodes))
                {
                    return new APIRequst<int>
                    {
                        Code = RequstCode.成功,
                        Msg = $"ID为{request.ProcessRouteId}的工艺路线没有nodes数据",
                        Data = 0
                    };
                }

                // 解析nodes字段中的JSON数据
                List<ProcessFlowNode> nodes = null;
                
                try
                {
                    // 处理可能的两种格式：直接是nodes数组或者包含nodes属性的对象
                    if (processroute.nodes.TrimStart().StartsWith("{"))
                    {
                        var flowChart = JsonConvert.DeserializeObject<FlowChartModel>(processroute.nodes);
                        nodes = flowChart?.nodes ?? new List<ProcessFlowNode>();
                    }
                    else
                    {
                        nodes = JsonConvert.DeserializeObject<List<ProcessFlowNode>>(processroute.nodes) ?? new List<ProcessFlowNode>();
                    }
                }
                catch (JsonException ex)
                {
                    return new APIRequst<int>
                    {
                        Code = RequstCode.成功,
                        Msg = $"JSON解析错误：{ex.Message}",
                        Data = 0
                    };
                }

                if (nodes == null || nodes.Count == 0)
                {
                    return new APIRequst<int>
                    {
                        Code = RequstCode.成功,
                        Msg = $"ID为{request.ProcessRouteId}的工艺路线nodes数据为空",
                        Data = 0
                    };
                }

                // 存储要添加的节点信息
                var nodesToAdd = new List<Nodeinfo>();
                
                // 遍历所有节点，建立节点关系
                for (int i = 0; i < nodes.Count; i++)
                {
                    var node = nodes[i];
                    var nodeName = GetNodeName(node);
                    
                    // 确定上一节点和下一节点
                    var nodeLast = i > 0 ? GetNodeName(nodes[i - 1]) : "";
                    var nodeNext = i < nodes.Count - 1 ? GetNodeName(nodes[i + 1]) : "";

                    // 创建Nodeinfo对象
                    nodesToAdd.Add(new Nodeinfo
                    {
                        NodeName = nodeName,
                        NodeLast = nodeLast,
                        NodeNext = nodeNext
                    });
                }

                // 批量添加节点信息到数据库
                var addedCount = await nodeRepository.AddRange(nodesToAdd);
                
                return new APIRequst<int>
                {
                    Code = RequstCode.成功,
                    Msg = $"成功添加{addedCount}个节点信息到节点表",
                    Data = addedCount
                };
            }
            catch (Exception ex)
            {
                return new APIRequst<int>
                {
                    Code = RequstCode.成功,
                    Msg = $"处理过程中发生错误：{ex.Message}",
                    Data = 0
                };
            }
        }

        // 辅助方法：从节点对象中获取节点名称
        private string GetNodeName(ProcessFlowNode node)
        {
            if (node.text != null && !string.IsNullOrEmpty(node.text.value))
                return node.text.value;
            
            if (node.properties != null)
            {
                if (!string.IsNullOrEmpty(node.properties.start))
                    return node.properties.start;
                if (!string.IsNullOrEmpty(node.properties.CustomRect))
                    return node.properties.CustomRect;
            }
            
            // 如果都没有，使用节点类型作为名称
            return $"{node.type}_{node.id.Substring(0, 5)}";
        }

        // JSON结构匹配的模型类
        private class ProcessFlowNode
        {
            public string id { get; set; }
            public string type { get; set; }
            public double x { get; set; }
            public double y { get; set; }
            public NodeProperties properties { get; set; }
            public NodeText text { get; set; }
        }

        private class NodeProperties
        {
            public string start { get; set; }
            public int width { get; set; }
            public int height { get; set; }
            public string CustomRect { get; set; }
            public string PropValue { get; set; }
        }

        private class NodeText
        {
            public double x { get; set; }
            public double y { get; set; }
            public string value { get; set; }
        }

        private class FlowChartModel
        {
            public List<ProcessFlowNode> nodes { get; set; }
        }
    }
}
